<!--
 * @Author: your name
 * @Date: 2020-03-26 09:41:08
 * @LastEditTime: 2020-03-26 09:41:10
 * @LastEditors: Please set LastEditors
 * @Description: 小黑猪
 -->
<template>
  <div>
    <van-form class="black-pig">
      <van-field
        v-model="ruleForm.mobile"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
      />
      <van-field
        v-model="ruleForm.password"
        type="password"
        label="密码"
        placeholder="请填写密码"
        clearable
      />
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <van-field name="radio" label="任务类型">
        <template #input>
          <van-radio-group v-model="type" direction="horizontal">
            <van-radio
              v-for="(option, index) in typeOptions"
              :key="index"
              :name="option.type"
              checked-color="#e4393c"
            >{{ option.label }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-cell-group>
        <van-cell
          class="van-cell__tip"
          v-for="(content, index) in returnContent"
          :key="index"
          :title="content"
        />
      </van-cell-group>
    </van-form>
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onStart">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>
  </div>
</template>

<script>
import { alertMsg, saveInfo, audio } from "@/utils/index";
export default {
  name: "BlackPig",
  props: {
    index: {
      type: String,
      default: ""
    },
    item: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      ruleForm: {
        mobile: "18745901723",
        password: "t4686986",
        grantType: "Password"
      },
      IntervalTime: 5,
      type: "https://hzapi.ka5a.com/memberSubTaskQueue",
      typeOptions: [
        { label: "我要买", type: "https://hzapi.ka5a.com/memberSubTaskQueue" },
        {
          label: "活动单",
          type: "https://hzapi.ka5a.com/memberSubTaskActivityQueue"
        },
        {
          label: "我要找",
          type: "https://hzapi.ka5a.com/memberSubTaskCollectionQueue"
        }
      ],
      startFlag: false,
      accessToken: "",
      timer: null,
      taskId: "",
      returnContent: [],
      iconItems: [],
      isAcceptSuc: false,
      activeIndex: ""
    };
  },
  watch: {
    // 监听接单状态
    startFlag() {
      if (this.item.index === 30 && this.index !== "") {
        this.$emit("changeOpened", {
          index: this.index,

          status: this.isAcceptSuc
            ? "已接单"
            : this.startFlag
            ? "已启动"
            : "待启动",
          startFlag: this.startFlag,
          content: this.returnContent
        });
      }
    },
    returnContent() {
      if (this.item.index === 30) {
        if (this.returnContent.length >= 10) {
          this.returnContent = this.returnContent.filter((item, i) => i < 5);
        }
      }
    },
    // 监听当前索引
    index() {
      if (this.item.index === 30 && this.index !== "") {
        this.activeIndex = this.index;
        // 获取保存账号信息
        this.ruleForm.mobile = this.item.user;
        this.ruleForm.password = this.item.pass;
        this.type =
          this.item.type || "https://hzapi.ka5a.com/memberSubTaskQueue";

        // 如为 已接单 => 改变状态
        if (this.item.opened === "已接单") {
          this.$emit("changeOpened", {
            index: this.index,

            status: "待启动",
            startFlag: this.startFlag,
            content: this.returnContent
          });
        }
      }
    }
  },
  created() {
    if (this.item.index === 30 && this.index !== "") {
      this.activeIndex = this.index;
      // 获取保存账号信息
      this.ruleForm.mobile = this.item.user;
      this.ruleForm.password = this.item.pass;
      this.type = this.item.type || "https://hzapi.ka5a.com/memberSubTaskQueue";
    }
  },
  methods: {
    // 登录 => 接单
    onStart() {
      this.onLogin();
    },
    // 登录
    onLogin() {
      const _this = this;
      if (!this.startFlag) {
        this.accessToken = "";
        this.returnContent = [];
        this.startFlag = true;
        this.returnContent.unshift(alertMsg("正在登录"));
        // 异步登录
        this.$ajax({
          url: "https://hzapi.ka5a.com/auth",
          type: "post",
          ajaxData: {
            values: _this.ruleForm
          },
          method: res => {
            if (res) {
              // 登录成功  => 保存账号信息
              saveInfo({
                user: _this.ruleForm.mobile,
                pass: _this.ruleForm.password,
                type: _this.type,
                index: _this.index
              });
              _this.returnContent.unshift(alertMsg("登录成功"));
              _this.accessToken = res.tokenType + " " + res.accessToken;
              _this.onGetTaskList(_this);
            } else {
              _this.returnContent.unshift(alertMsg("登录异常，重新登录中..."));
              _this.startFlag = false;
              _this.onLogin();
            }
          }
        });
      } else {
        this.returnContent.unshift(alertMsg("接单取消"));
        clearInterval(_this.timer);
        this.startFlag = false;
        this.isAcceptSuc = false;
        this.$toast({ message: "已停止接单" });
      }
    },
    // 任务列表
    onGetTaskList(_this) {
      clearInterval(_this.timer);
      _this.returnContent.unshift(alertMsg("获取任务中..."));
      _this.taskId = "";
      _this.$axios
        .post(
          _this.type,
          {},
          {
            headers: {
              "content-type": "application/json",
              authorization: _this.accessToken
            }
          }
        )
        .then(res => {
          if (res) {
            _this.onGetOrder(_this);
          } else {
            _this.timer = setInterval(() => {
              if (_this.startFlag) {
                _this.onGetTaskList(_this);
              }
            }, _this.IntervalTime * 1000);
          }
        })
        .catch(() => {
          _this.timer = setInterval(() => {
            if (_this.startFlag) {
              _this.onGetTaskList(_this);
            }
          }, _this.IntervalTime * 1000);
        });
    },
    // 接单
    onGetOrder(_this) {
      _this.returnContent.unshift(alertMsg("正在接单"));
      _this.$axios
        .put(
          _this.type === "https://hzapi.ka5a.com/memberSubTaskCollectionQueue"
            ? "https://hzapi.ka5a.com/subTaskCollection"
            : "https://hzapi.ka5a.com/subTask",
          {
            subTaskCollectionStatus: "Check",
            subTaskStatus: "Check"
          },
          {
            headers: {
              "content-type": "application/json",
              authorization: _this.accessToken
            }
          }
        )
        .then(res => {
          if (res) {
            _this.returnContent.unshift(alertMsg("接单成功，请前往做单..."));
            audio();
            _this.isAcceptSuc = true;
            _this.startFlag = false;
            _this.$emit("changeOpened", {
              index: _this.activeIndex,
              status: "已接单",
              startFlag: false,
              content: ["接单成功，请前往做单..."]
            });
          } else {
            _this.timer = setInterval(() => {
              if (_this.startFlag) {
                _this.onGetTaskList(_this);
              }
            }, _this.IntervalTime * 1000);
          }
        });
    }
  }
};
</script>
